import { createForm } from "@formily/core";
import { createSchemaField } from "@formily/react";
import { TreeNode } from "@bill_law6/designable-core";
import { transformToSchema } from "@bill_law6/designable-formily-transformer";
import React, { useMemo } from "react";
import * as components from "./components";
import { Form } from "@bill_law6/formily-shadcn/components/Form";

// Simple ErrorBoundary wrapper component
class ErrorBoundary extends React.Component<
  { children: React.ReactNode },
  { hasError: boolean }
> {
  constructor(props: { children: React.ReactNode }) {
    super(props);
    this.state = { hasError: false };
  }

  static getDerivedStateFromError(_error: Error) {
    return { hasError: true };
  }

  componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
    console.error('PreviewWidget ErrorBoundary caught an error:', error, errorInfo);
  }

  render() {
    if (this.state.hasError) {
      return <div>Preview failed to render.</div>;
    }

    return this.props.children;
  }
}

const SchemaField = createSchemaField({
  components,
});

export interface IPreviewWidgetProps {
  tree: TreeNode;
}

export const PreviewWidget: React.FC<IPreviewWidgetProps> = (props) => {
  const form = useMemo(() => createForm(), []);
  const { form: formProps, schema } = transformToSchema(props.tree);
  return (
    <ErrorBoundary>
      <Form {...formProps} form={form}>
        <SchemaField schema={schema} />
      </Form>
    </ErrorBoundary>
  );
};
